const app = getApp()
const global = app.globalData;
var util = require('../../utils/util.js');
const bleUtil = require('../../utils/bu01BleUtil.js')
const bu01Reader = require('../../utils/bu01Reader.js')
const errorCode = require('../../utils/errorCode.js')
var Promise = require('../../utils/es6-promise.js')

var bleParams = {
  connectedDeviceId: '',
  serviceId: '',
  characteristicId: ''
}
var timeTask;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerImg: [{
        link: '',
        imgs: '../../images/head.jpg'
      },
      {
        link: '',
        imgs: '../../images/head2.jpg'
      },
    ],

    deviceCode: '',
    goodsinfo: '',
    thumbUrl: null,
    queryresult: '',
    time: 0,
    orderid: '',
    orderStatus: 2,
    firstTime: 0,
    isRole: 0,
    password: '',
    available: false,
    init: false
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.error = new errorCode.ErrorCode()
    wx.removeStorageSync("deviceCode")
    wx.removeStorageSync("token")
    console.log(options);
    if (options.q){
      var res = decodeURIComponent(options.q);
      
      var startIndex = res.indexOf("device_id=");
      var deviceCode = res.substring(startIndex + 10);
      this.setData({
        deviceCode: deviceCode
      })
      app.globalData.deviceCode = deviceCode;
    }
    wx.getSystemInfo({
      success: function (res) {
        app.globalData.platform = res.platform
        if (res.SDKVersion < '1.6.0') {
          wx.showModal({
            title: '当前微信版本过低',
            content: '为了能够正常的使用本程序，请更新微信客户端',
            showCancel: false,
            confirmText: '我知道了',
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
    let token = wx.getStorageSync("token")
    let _this = this
    let code = ''
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKe          
        if (res.code) {
          wx.request({
            url: global.APIURL + 'api/v1/login?code=' + res.code,
            data: '',
            success: function (res) {
              console.log(res)
              if (res.data.code == '200') {
                wx.setStorageSync("token", res.data.data)
                //_this.submitUserInfo();
                _this.queryRole()
                _this.getIndex();
                _this.getdevice();
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);
        }
      }
    })
  },
  initBlt(callback) {
    console.log('初始化调用.....')
    var that = this
    //连接蓝牙
    if (!app.globalData.connection ) {
      bleParams.deviceCode = app.globalData.deviceCode;
      if (bleParams.deviceCode){
        that.ble = new bleUtil.BU01BleUtil(bleParams)
        that.ble.iniBle()
          .then(() => {
            that.ble.findDevices(deviceId => {
              that.ble.connect(deviceId)
                .then(() => {
                  if (app.globalData.connectedDeviceId) {
                    wx.hideLoading()
                    this.reader = new bu01Reader.BU01Reader()
                    this.reader.monitor()
                    this.reader.sendInitCmd().then((res) => {
                      console.log('初始化密码', res)
                      app.globalData.password = res;
                    });
                    callback();
                  }
                })
            })
          })
          .catch(res => {
            wx.hideLoading()
            console.log('初始化蓝牙失败', res)
            if (getApp().globalData.platform == 'ios') {
              that.error.getErrorMsg('初始化蓝牙失败', res)
            } else {
              that.error.getErrorMsg('初始化蓝牙失败', 10001)
            }
            app.globalData.discovering = false
          })
      }else{

      }
    } else if (app.globalData.available) {
      this.reader = new bu01Reader.BU01Reader()
      this.reader.monitor()
      callback();
    }
  },
  
  getCaption(obj) {
    var index = obj.lastIndexOf("\?");
    obj = obj.substring(index + 1, obj.length);
    return obj;
  },
  // 提交用户信息
  submitUserInfo() {
    // 获取个人信息 无个人信息跳授权
    let userInfo = wx.getStorageSync("userInfo")
    if (userInfo == '') {
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },
  queryRole() {
    let that = this
    let token = wx.getStorageSync("token")
    wx.request({
      url: global.APIURL + 'api/v1/role?deviceCode=' + app.globalData.deviceCode,
      header: {
        'Authorization': token
      },
      data:'',
      method: 'GET',
      success: function (res) {
        if (res.data.code == '200') {
          that.setData({
            isRole: 1,
            password: res.data.data
          })
          wx.setStorageSync("isRole", 1)
        }
      }
    })
  },
  getIndex() {
    let _this = this
    let token = wx.getStorageSync("token")
    if (token) {
      wx.request({
        url: global.APIURL + 'api/v1/index',
        data: '',
        header: {
          'Authorization': token
        },
        success: function(res) {
          if (res.data.code == '200') {
            _this.setData({
              bannerImg: res.data.data
            })
            global.bannerImg = res.data.data;
          } else if (res.data.code == '700') {
            wx.clearStorageSync()
            wx.navigateTo({
              url: '../login/login',
            })
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getdevice();
    this.queryRole()
  },
  // 补货
  sendReplenishmentCmd() {
    let token = wx.getStorageSync("token")
    this.initBlt(() => {
      this.reader.sendReplenishmentCmd(app.globalData.password + '1').then((res)=>{
       if (res) {
         if(res=='0'){
           var parameter = {
             deviceCode: app.globalData.deviceCode
           }
           // 修改状态
           wx.request({
             url: global.APIURL + 'api/v1/goods/stock',
             data: parameter,
             header: {
               'Authorization': token,
               'Content-Type': 'application/x-www-form-urlencoded'
             },
             method: 'POST',
             success: function (res1) {
               if (res1.data.code == '200') {
                 util.toast('补货成功~')
               }
             }
           })
         }else{
           util.toast('开门失败!')
         }
       }
     })
    })
  },
  getdevice() {
    let _this = this
    let token = wx.getStorageSync("token")
    if (token) {
      wx.request({
        url: global.APIURL + 'api/v1/goods',
        header: {
          'Authorization': token,
        },
        success: function(res) {
          if (res.data.code == '200') {
            _this.setData({
              goodsinfo: res.data.data,
              labelname: res.data.data.labelname.split(","),
              thumbUrl: res.data.data.thumbUrl.split(",")
            })
          }
        }
      })
    }
  },
  buy(e) {
    let _this = this
    let goodsId = e.currentTarget.dataset.goods.id;
    //判断是否扫描了设备
    let deviceCode = app.globalData.deviceCode;


    if (deviceCode){
      this.initBlt(()=>{
        _this.checkNum(goodsId)
      })
    }else{
      wx.scanCode({
        success: (res) => {
          console.log(res.result)
          var startIndex = res.result.indexOf("device_id=");
          var code = res.result.substring(startIndex + 10);
          app.globalData.deviceCode = code;
          _this.buy(e);
          _this.queryRole();
        }
      })
    }
  },
  checkNum(id) {
    wx.showLoading({
      title: '查询库存中',
      mask: true
    })
    let _this = this
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    wx.request({
      url: global.APIURL + 'api/v1/goods/stock?deviceCode=' + deviceCode,
      header: {
        'Authorization': token,
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == '200') {
          if (res.data.data >= 1) {
            console.log(res.data.data)
            _this.buyCom(id)
          } else {
            util.toast('库存不足~')
          }
        }else{
          util.toast('未绑定设备~')
        }
      }
    })
  },
  buyCom(id) {
    let _this = this
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    wx.showLoading({
      title: '下单中...',
      mask: true
    })
    var parameter = {
      deviceCode: deviceCode,
      goodsId: id
    };
    wx.request({
      url: global.APIURL + 'api/v1/order',
      data: parameter,
      header: {
        'Authorization': token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        wx.hideLoading();
        if (res.data.code == '200') {
          let result = res.data.data.result
          _this.setData({
            orderid: res.data.data.orderid
          })
          _this.getStatus()
          wx.requestPayment({
            timeStamp: result.timeStamp,
            nonceStr: result.nonceStr,
            package: result.packageValue,
            signType: result.signType,
            paySign: result.paySign,
            success(res2) {
             
            },
            fail(error) {
              util.toast('未付款，已取消订单')
            }
          })
        }
      }
    })
  },
  getStatus() {
    let _this = this
    wx.showLoading({
      title: '正在出套中',
      mask: true
    })
    _this.data.time = 0;
     timeTask = setInterval(function() {
      _this.data.time++;
      _this.queryresult()
      if (_this.data.time == '60') {
        util.toast('已超时')
        clearInterval(timeTask);
      }
    }, 1000)
  },
  queryresult() {
    let _this = this
    let token = wx.getStorageSync("token")
    let deviceCode = app.globalData.deviceCode
    wx.request({
      url: global.APIURL + '/api/v1/order/status?orderId=' + _this.data.orderid,
      header: {
        'Authorization': token,
      },
      success: function(res) {
        if (res.data.code == '200') {
          console.log(res.data.data)
          var password = app.globalData.password + app.globalData.password
          _this.setData({
            orderStatus: res.data.data.orderStatus
          })
          if (res.data.data.orderStatus == '0') {
            clearInterval(timeTask);
            // 发起指令之后 修改订单状态
            // var log = lanyaModule.sendSaleCmd(res.data.data.password.currentPassword + res.data.data.password.nextPassword + '1')
            if (_this.data.firstTime == 0) {
              _this.setData({
                firstTime: 1
              })
              // lanyaModule.sendRechargeCmd('1234561234561')
              console.log(password)
              _this.reader.sendSaleCmd(password + '1')   
              .then(rr => {
                wx.hideLoading();
                console.log("收到数据"+rr);
                
                _this.reader.sendRechargeCmd(password + '0')
                .then(()=>{
                  return _this.reader.sendRechargeCmd(password + '2');
                })
                .then(() => {
                   _this.reader.sendSaleCmd(password+ '0')
                  _this.ble.closeBle();
                })

               
                if (rr!="0") {
                  wx.showModal({
                    title: "购买结果",
                    content: '购买失败，请联系工作人员！',
                    showCancel: false,
                    confirmText: '确定'
                  })
                 
                }
              
                var parameter = {
                  orderId: _this.data.orderid,
                  status: rr=="0" ? '1' : '4',
                  msg: rr
                }
                // 修改状态
                wx.request({
                  url: global.APIURL + 'api/v1/order/status',
                  data: parameter,
                  header: {
                    'Authorization': token,
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  success: function (res1) {
                    if (res1.data.code == '200') {
                      wx.hideLoading();
                      util.toast('操作完成');
                      _this.setData({
                        firstTime: 0
                      })
                    }
                  }
                })
                }).catch(res => {
                  wx.hideLoading()
                  util.toast('数据接收失败');
                })
              
            }
          }
        } else {
          util.toast(res.message);
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(this.data.queryresult)
    if (app.globalData.available && app.globalData.discovering) {
      this.stopSearchBle()
    }
  },
  stopSearchBle() {
    this.ble.stop()
      .catch((res) => {
        this.error.getErrorMsg('停止搜索蓝牙出错', res)
      })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.data.queryresult)
    if (app.globalData.available) {
      if (app.globalData.discovering) {
        this.stopSearchBle()
      }
    } 
    if (app.globalData.connection) {
      //关闭蓝牙适配器
      this.ble.closeBle()
        .catch((res) => {
          this.error.getErrorMsg('关闭蓝牙出错', res)
        })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})